<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>div水平垂直居中示例</title>
    <style>
        /* 通用样式 */
        .demo-container {
            margin: 20px 0;
            border: 1px solid #ccc;
            height: 200px;
            position: relative;
        }
        
        .demo-title {
            padding: 5px;
            background-color: #f0f0f0;
            font-weight: bold;
        }
        
        .center-box {
            background-color: #3498db;
            color: white;
            text-align: center;
            width: 100px;
            height: 100px;
        }
        
        /* 方法1: Flexbox */
        .method1 {
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        /* 方法2: Grid */
        .method2 {
            display: grid;
            place-items: center;
        }
        
        /* 方法3: 绝对定位 + transform */
        .method3 .center-box {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
        
        /* 方法4: 绝对定位 + 负边距 (需要已知宽高) */
        .method4 .center-box {
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -50px; /* 高度的一半 */
            margin-left: -50px; /* 宽度的一半 */
        }
        
        /* 方法5: 绝对定位 + 四个方向0 + margin:auto */
        .method5 .center-box {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto;
        }
        
        /* 方法6: 表格布局 */
        .method6 {
            display: table-cell;
            vertical-align: middle;
            text-align: center;
            width: 100%;
        }
        
        .method6 .center-box {
            display: inline-block;
        }
    </style>
</head>
<body>
    <h3>div水平垂直居中的几种方法</h3>
    
    <div class="demo-container method1">
        <div class="demo-title">方法1: Flexbox</div>
        <div class="center-box">Flexbox</div>
    </div>
    
    <div class="demo-container method2">
        <div class="demo-title">方法2: Grid</div>
        <div class="center-box">Grid</div>
    </div>
    
    <div class="demo-container method3">
        <div class="demo-title">方法3: 绝对定位 + transform</div>
        <div class="center-box">绝对定位+transform</div>
    </div>
    
    <div class="demo-container method4">
        <div class="demo-title">方法4: 绝对定位 + 负边距</div>
        <div class="center-box">绝对定位+负边距</div>
    </div>
    
    <div class="demo-container method5">
        <div class="demo-title">方法5: 绝对定位 + 四个方向0 + margin:auto</div>
        <div class="center-box">绝对定位+margin</div>
    </div>
    
    <div class="demo-container method6">
        <div class="demo-title">方法6: 表格布局</div>
        <div class="center-box">表格布局</div>
    </div>
</body>
</html>